//
// client.cpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>


using boost::asio::ip::tcp;


void workerFunc(std::string message, tcp::socket *socket)
{


	std::cout << "Worker: running" << std::endl;

	try
	{
		/* if (argc != 2)
		{
		std::cerr << "Usage: client <host>" << std::endl;
		return 1;
		}*/



		for (;;)
		{
			boost::array<char, 32> buf;
			boost::system::error_code error;

			boost::system::error_code ignored_error;
			boost::asio::write(*socket, boost::asio::buffer(message), ignored_error);





			size_t len = socket->read_some(boost::asio::buffer(buf), error);

			std::cout.write(message.c_str(), 3);
			std::cout.write(buf.data(), len);
			std::cout.write("\n", 1);

			std::string result(buf.data());

			if (error == boost::asio::error::eof)
				break; // Connection closed cleanly by peer.
			else if (error)
				throw boost::system::system_error(error); // Some other error.

			

			
		
		}
	}
	catch (std::exception& e)
	{
		std::cerr << e.what() << std::endl;
	}

	std::cout << "Worker: finished" << std::endl;
}


int main2(int argc, char* argv[])
{

	boost::asio::io_service io_service;

	tcp::resolver resolver(io_service);
	tcp::resolver::query query("127.0.0.1", "daytime");
	tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

	tcp::socket socket(io_service);
	//boost::asio::connect(socket, endpoint_iterator);

	tcp::endpoint connectionEndpoint(endpoint_iterator->endpoint().address(), 11180);
	boost::system::error_code ec;
	socket.connect(connectionEndpoint, ec);

	tcp::socket socket2(io_service);
	socket2.connect(connectionEndpoint, ec);

	boost::thread workerThread1(workerFunc,"alma2",&socket);
	boost::thread workerThread2(workerFunc,"korte",&socket2);

	workerThread1.join();
	workerThread2.join();

	return 0;
}


